package com.yonyougov.devops.cruxcisupport.k8s.rest.thread;

import com.yonyougov.devops.cruxcisupport.appenv.AppEnvService;
import com.yonyougov.devops.cruxcisupport.appenv.vo.AppEnvVo;
import com.yonyougov.devops.cruxcisupport.deployhistory.DeployHisEntity;
import com.yonyougov.devops.cruxcisupport.deployhistory.DeployHisService;
import com.yonyougov.devops.cruxcisupport.deployhistory.dto.DeployHisRecordDto;
import com.yonyougov.devops.cruxcisupport.user.UserService;
import com.yonyougov.devops.cruxcisupport.version.VersionEntity;
import com.yonyougov.devops.cruxcisupport.version.VersionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 记录部署历史线程
 */
@Slf4j
public class DeployHisRecordThread extends Thread {
    private VersionService versionService;
    private UserService userService;
    private DeployHisService deployHisService;
    private List<DeployHisRecordDto> deployHisRecordDtoList;
    private AppEnvService appEnvService;

    public DeployHisRecordThread(AppEnvService appEnvService, VersionService versionService, UserService userService, DeployHisService deployHisService, List<DeployHisRecordDto> deployHisRecordDtoList) {
        this.appEnvService = appEnvService;
        this.versionService = versionService;
        this.userService = userService;
        this.deployHisService = deployHisService;
        this.deployHisRecordDtoList = deployHisRecordDtoList;
    }

    @Override
    public void run() {
        List<DeployHisEntity> deployHisEntityList = deployHisRecordDtoList.stream().map(deployHisRecordDto -> {
            AppEnvVo appEnvVo = appEnvService.findByEnvNameAndAppName(deployHisRecordDto.getEnvName(), deployHisRecordDto.getAppName());
            VersionEntity versionEntity = versionService.findBy(VersionEntity.builder()
                    .versionName(appEnvVo.getPackageVersion())
                    .appId(appEnvVo.getAppId())
                    .build());
            return DeployHisEntity.builder()
                    .id(deployHisService.idGenerat())
                    .envId(appEnvVo.getEnvId())
                    .appId(appEnvVo.getAppId())
                    .operator(userService.getCurrentUser().getId())
                    .versionId((StringUtils.isBlank(appEnvVo.getPackageVersion()) || null == versionEntity) ? new BigInteger("0") : versionEntity.getId())
                    .createTime(new Date())
                    .operationType(deployHisRecordDto.getDeployHisOperationTypeEnum().getCode())
                    .build();

        }).collect(Collectors.toList());
        log.debug("开始插入部署历史表");
        deployHisService.batchAddDeployHistory(deployHisEntityList);
        log.debug("结束插入部署历史表");
    }
}
